<template>
  <div class="customTable" v-loading="tableLoading">
    <!-- 工具栏 -->
    <div class="action">
      <div class="action-left">
        <!--  class="mr-12" 左边距取消 -->
        <tableToolDialog />
        <slot name="action-left"></slot>
      </div>
      <div class="action-right">
        <slot name="action-right"></slot>
      </div>
    </div>
    <div class="table-top">
      <slot name="table-top"></slot>
    </div>
    <!-- 表格 -->
    <el-table
      ref="tableRef"
      id="tableRefCustomId"
      :data="tableData"
      style="width: 100%"
      :border="true"
      :row-class-name="dispatchClassName"
      row-key="orderId"
      :tree-props="{
        children: 'childrens',
        checkStrictly: true
      }"
      @row-click="handleRowClick"
      @row-dblclick="handleRowDblclick"
      @selection-change="handleSelectionChange"
    >
      <!-- 选择列 -->
      <el-table-column v-if="showSelection" type="selection" width="55" />

      <!-- 动态列 -->
      <template v-for="col in columns" :key="col.prop">
        <el-table-column v-bind="col">
          <template v-if="col.formatter" #default="{ row, column, $index }">
            {{ col.formatter(row, column, $index) }}
          </template>
          <template v-else-if="col.slot" #default="scope">
            <slot :name="col.slot" v-bind="scope"></slot>
          </template>
        </el-table-column>
      </template>

      <!-- 空数据 -->
      <template #empty>
        <el-result style="margin: 100px auto" sub-title="暂无订单">
          <template #icon>
            <el-image style="width: 150px" :src="noorder" />
          </template>
        </el-result>
      </template>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-if="showPagination"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="defaultParams.pageSize"
        :current-page="defaultParams.pageNum"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineProps, defineEmits, defineExpose, computed } from 'vue';
import { topCustomStatusList, topStatusList } from '../../utils/order';
import { dayjs } from 'element-plus';
import noorder from '@/assets/images/noorder.png';
import useUserStore from '../../store/modules/user';
import { useRoute } from 'vue-router';

interface Column {
  prop: string;
  label: string;
  width?: number;
  minWidth?: number;
  fixed?: string | boolean;
  formatter?: (row: any, column: any, index: number) => string;
  slot?: string;
}

interface Props {
  actions?: (params: any) => Promise<any>;
  data?: any[];
  columns: Column[];
  showSelection?: boolean;
  showPagination?: boolean;
  resizable?: boolean;
  defaultParams?: object;
  autoRequest?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  autoRequest: true
});
const route = useRoute();
const emits = defineEmits(['selection-change', 'row-click', 'row-dblclick']);

// 数据与分页
const tableRef = ref();
const tableLoading = ref(false);
const tableData = ref<any[]>([]);
const total = ref(0);
const userStore = useUserStore();
const isCustomer = computed(() => userStore.roles.includes('customerService'));

// 组件管理参数
const defaultParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ...(props.defaultParams || {})
});

// 自定义查询参数
const paramsData = reactive<any>({});

// 样式存储
async function fetchData() {
  tableLoading.value = true;
  if (props.actions) {
    props.actions({ ...defaultParams, ...paramsData }).then((res) => {
      tableLoading.value = false;
      if (res.code === 200) {
        tableData.value = res.rows || [];

        total.value = parseInt(res.total || 0);
      }
    });
  } else {
    tableLoading.value = false;
    tableData.value = props.data || [];
  }
}

function handleSizeChange(val: number) {
  defaultParams.pageSize = val;
  fetchData();
}

function handleCurrentChange(val: number) {
  defaultParams.pageNum = val;
  fetchData();
}

// 供外部刷新
function refresh() {
  fetchData();
}

function search(params: any) {
  // 将 params 重置到 paramsData
  // 清空 paramsData
  Object.keys(paramsData).forEach((key) => {
    delete paramsData[key];
  });

  if (params?.today === 1) {
    const today = new Date();
    paramsData.params = {
      beginOrderTime: dayjs(today).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      endOrderTime: dayjs(today).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    };
    delete params.today;
  }

  Object.assign(paramsData, params);
  fetchData();
}

/** ============ 事件处理 ============ */
function handleSelectionChange(event: any) {
  emits('selection-change', event);
}

function handleRowClick(row: any) {
  emits('row-click', row);
}

function handleRowDblclick(row: any) {
  emits('row-dblclick', row);
}

// 平台订单：根据指定类型 映射 置顶状态类名
function getClassByIsFixed({ row }: any): string {
  const { topStatus, cTopStatus, topType = '', cTopType = '' } = row;
  const topValue = parseInt(isCustomer.value ? cTopStatus : topStatus);
  const typeValue = parseInt(isCustomer.value ? cTopType : topType);
  // 置顶状态下处理
  if (topValue == 1) {
    const item = topStatusList.find((i) => i?.value == typeValue);
    return item?.className || '';
  }

  return '';
}

// 平台客户：根据指定类型 映射 置顶状态类名
function getCustomerTopClassName({ row }: any): string {
  const { topStatus, topType = '' } = row;
  if (parseInt(topStatus || 0) === 1) {
    return topCustomStatusList.find((i) => i?.value == topType)?.className || '';
  }
  return '';
}

// 根据类型 映射 置顶方法
function dispatchClassName({ row }: any): string {
  // 销售：平台客户
  const isPlatformCustomer = route.path === '/platformCustomers/customers';
  // 平台订单
  const platformOrderPaths = [
    '/platformOrders/orders',
    '/platformOrders/rpOrders',
    '/customerService/order',
    '/customerService/repeatPurchaseOrder',
    '/customerService/appeal'
  ];
  const isPlatformOrder = platformOrderPaths.includes(route.path || '');
  // 平台客户
  if (isPlatformCustomer) {
    return getCustomerTopClassName({ row });
  }
  // 平台订单
  if (isPlatformOrder) {
    return getClassByIsFixed({ row });
  }

  return '';
}

onMounted(() => {
  // 是否自动请求 默认请求
  if (props.autoRequest !== false) {
    fetchData();
  }
});

defineExpose({ refresh, search });
</script>

<style lang="scss">
.customTable {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  /* 干掉 hover 的背景 */
  .el-table__row:hover > td {
    background-color: transparent !important;
  }

  /* 某些版本会给 hover 行加 hover-row 类，顺便一起干掉 */
  .el-table__row.hover-row > td {
    background-color: transparent !important;
  }

  /* 干掉 hover 产生的 z-index，避免行浮起来 */
  .el-table__row.hover-row,
  .el-table__row:hover {
    z-index: auto !important;
    position: static !important;
  }

  .action {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;

    .action-left {
      display: flex;
    }
  }

  .table-top {
  }

  #tableRefCustomId {
    flex: 1;
  }

  .pagination {
    margin-top: 12px;
    display: flex;
    justify-content: center;
    height: 50px;
  }

  // 跟踪置顶颜色
  // 默认白色
  .el-table__row {
    background-color: #fff !important;

    &.hover-row.hover-row {
      > td {
        background-color: inherit !important;
      }
    }
  }

  // 跟踪置顶黄色
  .yellow-class {
    background-color: #ffeec8 !important;

    &.hover-row.hover-row {
      > td {
        background-color: inherit !important;
      }
    }
  }

  // 退货/投诉置顶
  .red-class {
    background-color: #ffd9d6 !important;

    &.hover-row.hover-row {
      > td {
        background-color: inherit !important;
      }
    }
  }

  // 客户差评
  .black-class {
    background-color: #ceefff !important;
    &.hover-row.hover-row {
      > td {
        background-color: inherit !important;
      }
    }
  }
}
</style>
